package org.kongqian.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.kongqian.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        String token = request.getHeader("token");
        //校验
        if (StringUtils.isNotBlank(token)){

            Logininfo logininfo =(Logininfo) redisTemplate.opsForValue().get(token);
            if (Objects.nonNull(logininfo)){
                //进入这里说明是登录了的
                return true;
            }
        }
        // token为空，说明未登录过，也不能放行，要提示未登录  // 2.2 如果不存在，就提示未登录
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 在外面写好在拷贝进去
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
    }
}
